package com.nt.common.utils;

import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Description: 文件获取地址
 * Author: gzj
 * Date: 2024/5/21 9:25
 */
@Component
public class FileTokenUtils {

    @Bean
    public void echoUrlInit(){
        setECHOURL();
    }

    private static final String KEY = "hitbd2018";

    @Value("${echo.url}")
    private String echoUrl;

    @Getter
    private static String ECHOURL;

    public void setECHOURL() {
        FileTokenUtils.ECHOURL = echoUrl;
    }

    private static String md5(byte[] source) throws NoSuchAlgorithmException {
        char[] hexDigits = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(source);
        byte[] tmp = md.digest();
        char[] str = new char[32];
        int k = 0;

        for(int i = 0; i < 16; ++i) {
            str[k++] = hexDigits[tmp[i] >>> 4 & 15];
            str[k++] = hexDigits[tmp[i] & 15];
        }

        return new String(str);
    }


    private static String getToken(String remote_filename, int ts) throws  Exception {
        byte[] bsFilename = remote_filename.getBytes(StandardCharsets.UTF_8);
        byte[] bsKey = KEY.getBytes(StandardCharsets.UTF_8);
        byte[] bsTimestamp = (new Integer(ts)).toString().getBytes(StandardCharsets.UTF_8);
        byte[] buff = new byte[bsFilename.length + bsKey.length + bsTimestamp.length];
        System.arraycopy(bsFilename, 0, buff, 0, bsFilename.length);
        System.arraycopy(bsKey, 0, buff, bsFilename.length, bsKey.length);
        System.arraycopy(bsTimestamp, 0, buff, bsFilename.length + bsKey.length, bsTimestamp.length);
        return md5(buff);
    }

    public static String getUrl(String url)throws  Exception{
        if(url.contains("file/") && url.contains("?token")){
            url = url.substring(url.indexOf("file/")+5,url.indexOf("?token"));
        }
        int ts = (int) (System.currentTimeMillis() / 1000);
        String remoteFilename = url;
        String token = getToken(remoteFilename, ts);
        return FileTokenUtils.getECHOURL()+remoteFilename + "?token=" + token + "&ts=" + ts;
    }

}
